package com.inwavetech.os.util;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;

import com.inwavetech.os.R;

public class SyncUtils {
    private final Context context;
    private String contentAuthority;

    public SyncUtils(Context context) {
        this.context = context;
        contentAuthority = context.getString(R.string.content_authority);
    }

    public void registerSync() {
        long SYNC_INTERVAL = 30L * 60L; // 30 mins

        Account account = getAccount();
        ((AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE)).addAccountExplicitly(account, null, null);

        // configure account as syncable
        ContentResolver.setIsSyncable(account, contentAuthority, 1);
        // configure the account to sync automatically
        ContentResolver.setSyncAutomatically(account, contentAuthority, true);
        // configure the sync interval
        ContentResolver.addPeriodicSync(account, contentAuthority, new Bundle(), SYNC_INTERVAL);

        syncNow();
    }

    public void syncNow() {
        // Disable sync backoff and ignore sync preferences. In other words...perform sync NOW!
        Bundle bundle = new Bundle();
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        ContentResolver.requestSync(
                getAccount(),
                contentAuthority,
                bundle);
    }

    private Account getAccount() {
        return new Account(context.getString(R.string.account_name), context.getString(R.string.account_type));
    }
}
